import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import {prefix} from '@/api/url'
// const isTest = 0

// const baseURL = isTest ? process.env.VUE_APP_BASE_API :  

// 返回码列表
const resCodes = {
  success: '000000',
  failure: '000001',
  forbidden: '000403',
  remoteLogin: '000402',
  loginExpired: '000401',
}

// 阻止请求
// let stopRequest = false

// 退出登录
const doLogout = () => {
  // stopRequest = true
  setTimeout(() => {
    store.dispatch('user/doLogout')
    // stopRequest = false
  }, 500)
}

// 设置loading状态
const setLoading = beal => {
  store.dispatch('setLoading', beal)
}

// 显示报错信息
const showMessage = ({ success, msg }) =>
  Message({
    message: msg,
    type: success ? 'success' : 'warning',
    duration: 5 * 1000
  })

// 创建axios实例
const service = axios.create({
  baseURL: prefix, // api的base_url
  timeout: 10000, // 请求超时时间 10s
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
  // method
})

// request拦截器
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    }
    const { method, loading = true } = config || {}
    if (!method) {
      config.method = 'get'
    }
    if (loading) {
      setLoading(true)
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    setLoading(false)
    const { data = {}, config } = response || {}
    const { showMsg, method, formatRes = true } = config || {}

    if (!formatRes) {
      return response
    }

    const { retCode, retMsg } = data
    let isSuccess = false
 
    let sendData = {}
    switch (retCode) {
      case resCodes.success:
        // api返回的code
        isSuccess = true

        sendData = {
          success: isSuccess,
          msg: retMsg || '操作成功!',
          ...data
        }
        break
      case resCodes.remoteLogin:
      case resCodes.forbidden:
      case resCodes.loginExpired:
        doLogout()
        sendData = {
          success: isSuccess,
          msg: retMsg || '登录失效',
          ...data
        }
        break
      default:
        sendData = {
          success: isSuccess,
          msg: retMsg || (isSuccess ? '操作成功!' : '操作失败!'),
          ...data
        }
    }

    if (sendData.msg === resCodes.success) {
      sendData.msg = '操作成功!'
    }
    // api未返回data  默认显示message；showMsg 强制决定是否显示message
    if (
      showMsg ||
      (method.toLocaleLowerCase() === 'post' && showMsg !== false)
    ) {
      showMessage({
        success: sendData.success,
        msg: sendData.msg
      })
    }
    return sendData
  },

  error => {
    console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
